<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="login-popup">
      <view class="popup-header">
        <text class="popup-title">{{ getPopupTitle }}</text>
        <view class="close-btn" @click="closePopup">×</view>
      </view>
      
      <view class="popup-content">
        <!-- 选择登录方式页面 -->
        <view v-if="currentStep === 'choose'">
          <text class="popup-desc">登录后可享受更多权益</text>
          
          <view class="login-options">
            <button class="login-btn" @click="showUserLoginForm">用户登录/注册</button>
            <button class="login-btn merchant-btn" @click="showMerchantLoginForm">商家登录/注册</button>
            <button class="login-btn admin-btn" @click="showAdminLoginForm">管理员登录/注册</button>
          </view>
          
          <view class="skip-login" @click="skipLogin">
            <text>暂不登录，直接使用</text>
          </view>
        </view>
        
        <!-- 用户登录表单 -->
        <view v-else-if="currentStep === 'userLogin'">
          <view class="login-tabs">
            <view 
              class="login-tab" 
              :class="{'active': loginType === 1}" 
              @click="loginType = 1"
            >
              密码登录
            </view>
            <view 
              class="login-tab" 
              :class="{'active': loginType === 2}" 
              @click="loginType = 2"
            >
              验证码登录
            </view>
          </view>
          
          <!-- 密码登录表单 -->
          <view v-if="loginType === 1" class="login-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="dualBind" 
                placeholder="请输入用户名/手机号" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="loginForm.password" 
                placeholder="请输入密码" 
              />
            </view>
            <button 
              class="login-btn" 
              :disabled="isLoading"
              @click="handleUserLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <!-- 验证码登录表单 -->
          <view v-else class="login-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="loginForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item verify-code">
              <input 
                class="input" 
                type="text" 
                v-model="loginForm.verifyCode" 
                placeholder="请输入验证码"
                maxlength="4"
              />
              <button 
                class="code-btn" 
                :disabled="cooldown > 0" 
                @click="getVerifyCode"
              >
                {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
              </button>
            </view>
            <button 
              class="login-btn" 
              :disabled="isLoading"
              @click="handleUserLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'choose'">
              <text>返回</text>
            </view>
            <view class="register-link" @click="showRegisterForm">
              <text>注册账号</text>
            </view>
          </view>
        </view>
        
        <!-- 用户注册表单 -->
        <view v-else-if="currentStep === 'register'">
          <view class="section-title">用户注册</view>
          
          <view class="register-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="registerForm.username" 
                placeholder="请输入用户名" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="registerForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="registerForm.password" 
                placeholder="请输入密码（至少6位）" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="registerForm.confirmPassword" 
                placeholder="请确认密码" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="registerForm.email" 
                placeholder="请输入邮箱（选填）" 
              />
            </view>
            <button 
              class="login-btn" 
              :disabled="isLoading"
              @click="handleRegister"
            >
              {{ isLoading ? '注册中...' : '注册' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'userLogin'">
              <text>返回登录</text>
            </view>
          </view>
        </view>
        
        <!-- 商家登录表单 -->
        <view v-else-if="currentStep === 'merchantLogin'">
          <view class="login-tabs">
            <view 
              class="login-tab" 
              :class="{'active': merchantLoginType === 1}" 
              @click="merchantLoginType = 1"
            >
              密码登录
            </view>
            <view 
              class="login-tab" 
              :class="{'active': merchantLoginType === 2}" 
              @click="merchantLoginType = 2"
            >
              验证码登录
            </view>
          </view>
          
          <!-- 密码登录表单 -->
          <view v-if="merchantLoginType === 1" class="login-form">
            <view class="form-item">
			  <input
			    class="input" 
			    type="text" 
			    v-model="WBind" 
			    placeholder="请输入商家账号/手机号" 
			  />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="merchantLoginForm.password" 
                placeholder="请输入密码" 
              />
            </view>
            <button 
              class="login-btn merchant-btn" 
              :disabled="isLoading"
              @click="handleMerchantLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <!-- 验证码登录表单 -->
          <view v-else class="login-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="merchantLoginForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item verify-code">
              <input 
                class="input" 
                type="text" 
                v-model="merchantLoginForm.verifyCode" 
                placeholder="请输入验证码"
                maxlength="4"
              />
              <button 
                class="code-btn" 
                :disabled="merchantCooldown > 0" 
                @click="getMerchantVerifyCode"
              >
                {{ merchantCooldown > 0 ? `${merchantCooldown}s` : '获取验证码' }}
              </button>
            </view>
            <button 
              class="login-btn merchant-btn" 
              :disabled="isLoading"
              @click="handleMerchantLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'choose'">
              <text>返回</text>
            </view>
            <view class="register-link" @click="showMerchantRegisterForm">
              <text>注册商家账号</text>
            </view>
          </view>
        </view>
        
        <!-- 商家注册表单 -->
        <view v-else-if="currentStep === 'merchantRegister'">
          <view class="section-title">商家注册</view>
          
          <view class="register-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="merchantRegisterForm.username" 
                placeholder="请输入商家账号" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="merchantRegisterForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="merchantRegisterForm.password" 
                placeholder="请输入密码（至少6位）" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="merchantRegisterForm.confirmPassword" 
                placeholder="请确认密码" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="merchantRegisterForm.email" 
                placeholder="请输入邮箱（选填）" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="merchantRegisterForm.shopName" 
                placeholder="请输入店铺名称" 
              />
            </view>
            <button 
              class="login-btn merchant-btn" 
              :disabled="isLoading"
              @click="handleMerchantRegister"
            >
              {{ isLoading ? '注册中...' : '注册' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'merchantLogin'">
              <text>返回登录</text>
            </view>
          </view>
        </view>
        
        <!-- 管理员登录表单 -->
        <view v-else-if="currentStep === 'adminLogin'">
          <view class="login-tabs">
            <view 
              class="login-tab" 
              :class="{'active': adminLoginType === 1}" 
              @click="adminLoginType = 1"
            >
              密码登录
            </view>
            <view 
              class="login-tab" 
              :class="{'active': adminLoginType === 2}" 
              @click="adminLoginType = 2"
            >
              验证码登录
            </view>
          </view>
          
          <!-- 密码登录表单 -->
          <view v-if="adminLoginType === 1" class="login-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="adminLoginForm.username" 
                placeholder="请输入管理员账号" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="adminLoginForm.password" 
                placeholder="请输入密码" 
              />
            </view>
            <button 
              class="login-btn admin-btn" 
              :disabled="isLoading"
              @click="handleAdminLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <!-- 验证码登录表单 -->
          <view v-else class="login-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="adminLoginForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item verify-code">
              <input 
                class="input" 
                type="text" 
                v-model="adminLoginForm.verifyCode" 
                placeholder="请输入验证码"
                maxlength="6"
              />
              <button 
                class="code-btn" 
                :disabled="adminCooldown > 0" 
                @click="getAdminVerifyCode"
              >
                {{ adminCooldown > 0 ? `${adminCooldown}s` : '获取验证码' }}
              </button>
            </view>
            <button 
              class="login-btn admin-btn" 
              :disabled="isLoading"
              @click="handleAdminLogin"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'choose'">
              <text>返回</text>
            </view>
            <view class="register-link" @click="showAdminRegisterForm">
              <text>注册管理员账号</text>
            </view>
          </view>
        </view>
        
        <!-- 管理员注册表单 -->
        <view v-else-if="currentStep === 'adminRegister'">
          <view class="section-title">管理员注册</view>
          
          <view class="register-form">
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="adminRegisterForm.username" 
                placeholder="请输入管理员账号" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="text" 
                v-model="adminRegisterForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="adminRegisterForm.password" 
                placeholder="请输入密码（至少6位）" 
              />
            </view>
            <view class="form-item">
              <input 
                class="input" 
                type="password" 
                v-model="adminRegisterForm.confirmPassword" 
                placeholder="请确认密码" 
              />
            </view>
            <view class="form-item verify-code">
              <input 
                class="input" 
                type="text" 
                v-model="adminRegisterForm.verifyCode" 
                placeholder="请输入验证码"
                maxlength="6"
              />
              <button 
                class="code-btn" 
                :disabled="adminRegisterCooldown > 0" 
                @click="getAdminRegisterVerifyCode"
              >
                {{ adminRegisterCooldown > 0 ? `${adminRegisterCooldown}s` : '获取验证码' }}
              </button>
            </view>
            <button 
              class="login-btn admin-btn" 
              :disabled="isLoading"
              @click="handleAdminRegister"
            >
              {{ isLoading ? '注册中...' : '注册' }}
            </button>
          </view>
          
          <view class="action-links">
            <view class="back-link" @click="currentStep = 'adminLogin'">
              <text>返回登录</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </uni-popup>
</template>


<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue';
import { useUserStore } from '@/store/user';
import http from '@/utils/http/http.js';

const emit = defineEmits(['login-success']);
const popup = ref(null);
const userStore = useUserStore();
const currentStep = ref('choose'); // 'choose', 'userLogin', 'register', 'merchantLogin', 'merchantRegister', 'adminLogin', 'adminRegister'
const loginType = ref(1); // 1: 密码登录, 2: 验证码登录
const merchantLoginType = ref(1); // 1: 密码登录, 2: 验证码登录
const adminLoginType = ref(1); // 1: 密码登录, 2: 验证码登录
const isLoading = ref(false);
const cooldown = ref(0);
const merchantCooldown = ref(0);
const adminCooldown = ref(0);
const cooldownTimer = ref(null);
const merchantCooldownTimer = ref(null);
const adminCooldownTimer = ref(null);
const adminRegisterCooldownTimer = ref(null);

// 用户登录表单
const loginForm = ref({
  username: '',
  phone: '',
  password: '',
  verifyCode: ''
});

// 用户注册表单
const registerForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  email: ''
});

// 商家登录表单
const merchantLoginForm = ref({
  username: '',
  phone: '',
  password: '',
  verifyCode: ''
});

// 商家注册表单
const merchantRegisterForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  email: '',
  shopName: ''
});

// 管理员登录表单
const adminLoginForm = ref({
  username: '',
  phone: '',
  password: '',
  verifyCode: ''
});

// 管理员注册表单
const adminRegisterForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  verifyCode: ''
});

// 弹窗标题
const getPopupTitle = computed(() => {
  switch (currentStep.value) {
    case 'userLogin':
      return '用户登录';
    case 'register':
      return '用户注册';
    case 'merchantLogin':
      return '商家登录';
    case 'merchantRegister':
      return '商家注册';
    case 'adminLogin':
      return '管理员登录';
    case 'adminRegister':
      return '管理员注册';
    default:
      return '欢迎使用';
  }
});
merchantLoginForm.username
// 创建计算属性实现双向绑定
const WBind = computed({
  get: () => merchantLoginForm.value.username, // 读取 merchantLoginForm.username 的值
  set: (value) => {
    // 同时更新 merchantLoginForm.username和 merchantLoginForm.phone
    merchantLoginForm.value.username = value;
    merchantLoginForm.value.phone = value;
  }
});
// 创建计算属性实现双向绑定
const dualBind = computed({
  get: () => loginForm.value.username, // 读取 username 的值
  set: (value) => {
    // 同时更新 username 和 phone
    loginForm.value.username = value;
    loginForm.value.phone = value;
  }
});

// 打开弹窗
const open = () => {
  console.log('尝试打开登录弹窗');
  if (popup.value) {
    // 重置表单状态
    resetForm();
    popup.value.open();
    console.log('登录弹窗已打开');
  } else {
    console.error('登录弹窗组件引用为空');
  }
};

// 重置表单
const resetForm = () => {
  currentStep.value = 'choose';
  loginType.value = 1;
  merchantLoginType.value = 1;
  adminLoginType.value = 1;
  loginForm.value = {
    username: '',
    phone: '',
    password: '',
    verifyCode: ''
  };
  registerForm.value = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
    email: ''
  };
  merchantLoginForm.value = {
    username: '',
    phone: '',
    password: '',
    verifyCode: ''
  };
  merchantRegisterForm.value = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
    email: '',
    shopName: ''
  };
  adminLoginForm.value = {
    username: '',
    phone: '',
    password: '',
    verifyCode: ''
  };
  adminRegisterForm.value = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
    verifyCode: ''
  };
  isLoading.value = false;
};

// 关闭弹窗
const closePopup = () => {
  skipLogin();
};

// 显示用户登录表单
const showUserLoginForm = () => {
  currentStep.value = 'userLogin';
};

// 显示用户注册表单
const showRegisterForm = () => {
  currentStep.value = 'register';
};

// 显示商家登录表单
const showMerchantLoginForm = () => {
  currentStep.value = 'merchantLogin';
};

// 显示商家注册表单
const showMerchantRegisterForm = () => {
  currentStep.value = 'merchantRegister';
};

// 显示管理员登录表单
const showAdminLoginForm = () => {
  currentStep.value = 'adminLogin';
};

// 显示管理员注册表单
const showAdminRegisterForm = () => {
  currentStep.value = 'adminRegister';
};

// 获取用户验证码
const getVerifyCode = async () => {
  // 验证手机号
  if (!loginForm.value.phone || !/^1\d{10}$/.test(loginForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 调用获取验证码接口
    const response = await http.get(`/api/auth/sms-code?phone=${loginForm.value.phone}`);
    if (response.code === 200) {
      // 开始倒计时
      cooldown.value = 60;
      cooldownTimer.value = setInterval(() => {
        cooldown.value--;
        if (cooldown.value <= 0) {
          clearInterval(cooldownTimer.value);
        }
      }, 1000);
      
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: response.message || '获取验证码失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    uni.showToast({
      title: '获取验证码失败，请重试',
      icon: 'none'
    });
  }
};

// 获取商家验证码
const getMerchantVerifyCode = async () => {
  // 验证手机号
  if (!merchantLoginForm.value.phone || !/^1\d{10}$/.test(merchantLoginForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 调用获取验证码接口 - 商家专用接口
    const response = await http.get(`/api/merchant/auth/sms-code?phone=${merchantLoginForm.value.phone}`);
    if (response.code === 200) {
      // 开始倒计时
      merchantCooldown.value = 60;
      merchantCooldownTimer.value = setInterval(() => {
        merchantCooldown.value--;
        if (merchantCooldown.value <= 0) {
          clearInterval(merchantCooldownTimer.value);
        }
      }, 1000);
      
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: response.message || '获取验证码失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    uni.showToast({
      title: '获取验证码失败，请重试',
      icon: 'none'
    });
  }
};

// 获取管理员验证码
const getAdminVerifyCode = async () => {
  if (!adminLoginForm.value.phone || !/^1[3-9]\d{9}$/.test(adminLoginForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    const response = await http.post('/api/admin/sms/code', {
      phone: adminLoginForm.value.phone
    });
    
    if (response.code === 200) {
      adminCooldown.value = 60;
      adminCooldownTimer.value = setInterval(() => {
        adminCooldown.value--;
        if (adminCooldown.value <= 0) {
          clearInterval(adminCooldownTimer.value);
        }
      }, 1000);
      
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    });
  }
};

// 获取管理员注册验证码
const getAdminRegisterVerifyCode = async () => {
  if (!adminRegisterForm.value.phone || !/^1[3-9]\d{9}$/.test(adminRegisterForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    const response = await http.post('/api/admin/sms/code', {
      phone: adminRegisterForm.value.phone
    });
    
    if (response.code === 200) {
      adminRegisterCooldown.value = 60;
      adminRegisterCooldownTimer.value = setInterval(() => {
        adminRegisterCooldown.value--;
        if (adminRegisterCooldown.value <= 0) {
          clearInterval(adminRegisterCooldownTimer.value);
        }
      }, 1000);
      
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    });
  }
};

// 处理用户登录
const handleUserLogin = async () => {
  // 表单验证
  if (loginType.value === 1) {
    // 密码登录验证
    if ((!loginForm.value.username || loginForm.value.username.trim() === '') &&
        (!loginForm.value.phone || loginForm.value.phone.trim() === '')) {
      uni.showToast({
        title: '请输入用户名或手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!loginForm.value.password || loginForm.value.password.trim() === '') {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
  } else {
    // 验证码登录验证
    if (!loginForm.value.phone || !/^1\d{10}$/.test(loginForm.value.phone)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!loginForm.value.verifyCode || loginForm.value.verifyCode.trim() === '') {
      uni.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
  }
  
  // 执行登录
  isLoading.value = true;
  
  try {
    // 构建登录参数
    const loginData = {
      loginType: loginType.value,
      username: loginForm.value.username,
      phone: loginForm.value.phone,
      password: loginForm.value.password,
      verifyCode: loginForm.value.verifyCode
    };
    
    // 调用登录接口
    const response = await http.post('/api/auth/login', loginData);
    
    if (response.code === 200 && response.data) {
      // 登录成功，保存用户信息
      const userData = response.data.user;
      console.log("登录成功，用户数据:", userData);
      emit('login-success');
      // 构建存储的用户信息
      const userInfo = {
        id: userData.id,
        username: userData.username,
        phone: userData.phone,
        email: userData.email,
        avatar: userData.avatarUrl || '/static/placeholder.png',
        createTime: userData.createTime
      };
      
      // 保存用户信息到 store
      userStore.login('user', userInfo, response.data.token);
      
      // 关闭弹窗
      popup.value.close();
      
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 重要：确保在所有页面都能获取到最新的用户状态
      nextTick(() => {
        // 刷新当前页面数据
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage && currentPage.$vm && typeof currentPage.$vm.onShow === 'function') {
          currentPage.$vm.onShow();
        }
      });
    } else {
      // 显示错误信息
      uni.showToast({
        title: response.message || '登录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 处理用户注册
const handleRegister = async () => {
  // 表单验证
  if (!registerForm.value.username || registerForm.value.username.trim() === '') {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none'
    });
    return;
  }
  
  if (!registerForm.value.phone || !/^1\d{10}$/.test(registerForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  if (!registerForm.value.password || registerForm.value.password.length < 6) {
    uni.showToast({
      title: '密码不能少于6位',
      icon: 'none'
    });
    return;
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none'
    });
    return;
  }
  
  // 邮箱格式验证（如果填写了邮箱）
  if (registerForm.value.email && registerForm.value.email.trim() !== '') {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(registerForm.value.email)) {
      uni.showToast({
        title: '邮箱格式不正确',
        icon: 'none'
      });
      return;
    }
  }
  
  // 执行注册
  isLoading.value = true;
  
  try {
    // 构建注册参数
    const registerData = {
      username: registerForm.value.username,
      phone: registerForm.value.phone,
      password: registerForm.value.password,
      email: registerForm.value.email || null // 如果没有填写邮箱，传null
    };
    
    // 调用注册接口
    const response = await http.post('/api/users/register', registerData);
    
    if (response.code === 200 && response.data) {
      // 注册成功
      uni.showToast({
        title: '注册成功，请登录',
        icon: 'success'
      });
      
      // 自动填充登录表单
      loginForm.value.username = registerForm.value.username;
      loginForm.value.phone = registerForm.value.phone;
      loginForm.value.password = ''; // 出于安全考虑，不自动填充密码
      
      // 切换到登录页面
      currentStep.value = 'userLogin';
      loginType.value = 1; // 切换到密码登录
    } else {
      // 显示错误信息
      uni.showToast({
        title: response.message || '注册失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('注册失败:', error);
    uni.showToast({
      title: '注册失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 处理商家登录
const handleMerchantLogin = async () => {
  // 表单验证
  if (merchantLoginType.value === 1) {
    // 密码登录验证
    if (!merchantLoginForm.value.username || merchantLoginForm.value.username.trim() === '') {
      uni.showToast({
        title: '请输入商家账号',
        icon: 'none'
      });
      return;
    }
    
    if (!merchantLoginForm.value.password || merchantLoginForm.value.password.trim() === '') {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
  } else {
    // 验证码登录验证
    if (!merchantLoginForm.value.phone || !/^1\d{10}$/.test(merchantLoginForm.value.phone)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!merchantLoginForm.value.verifyCode || merchantLoginForm.value.verifyCode.trim() === '') {
      uni.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
  }
  
  // 执行登录
  isLoading.value = true;
  
  try {
    // 构建登录参数
    const loginData = {
      loginType: merchantLoginType.value,
      username: merchantLoginForm.value.username,
      phone: merchantLoginForm.value.phone,
      password: merchantLoginForm.value.password,
      verifyCode: merchantLoginForm.value.verifyCode
    };
    
    // 调用商家登录接口
    const response = await http.post('/api/admin/login', loginData);
    
    if (response.code === 200 && response.data) {
      // 登录成功，保存商家信息
      const merchantData = response.data;
      console.log("商家登录成功，数据:", merchantData);
      emit('login-success');
      
      // 构建存储的商家信息
      const merchantInfo = {
        //id: merchantData.id,
        username: merchantData.username,
        //shopName: merchantData.shopName,
        //phone: merchantData.phone,
        //email: merchantData.email,
        //avatar: merchantData.avatarUrl || '/static/merchant-placeholder.png',
        //status: merchantData.status,
        //createTime: merchantData.createTime
      };
      
      // 保存商家信息到 store
      userStore.login('merchant', merchantInfo, response.data.token);
      
      // 关闭弹窗
      popup.value.close();
      
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 跳转到商家中心
      uni.reLaunch({
        url: '/pages/merchant/dashboard'
      });
    } else {
      // 显示错误信息
      uni.showToast({
        title: response.message || '登录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('商家登录失败:', error);
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 处理商家注册
const handleMerchantRegister = async () => {
  // 表单验证
  if (!merchantRegisterForm.value.username || merchantRegisterForm.value.username.trim() === '') {
    uni.showToast({
      title: '请输入商家账号',
      icon: 'none'
    });
    return;
  }
  
  if (!merchantRegisterForm.value.phone || !/^1\d{10}$/.test(merchantRegisterForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  if (!merchantRegisterForm.value.password || merchantRegisterForm.value.password.length < 6) {
    uni.showToast({
      title: '密码不能少于6位',
      icon: 'none'
    });
    return;
  }
  
  if (merchantRegisterForm.value.password !== merchantRegisterForm.value.confirmPassword) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none'
    });
    return;
  }
  
  if (!merchantRegisterForm.value.shopName || merchantRegisterForm.value.shopName.trim() === '') {
    uni.showToast({
      title: '请输入店铺名称',
      icon: 'none'
    });
    return;
  }
  
  // 邮箱格式验证（如果填写了邮箱）
  if (merchantRegisterForm.value.email && merchantRegisterForm.value.email.trim() !== '') {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(merchantRegisterForm.value.email)) {
      uni.showToast({
        title: '邮箱格式不正确',
        icon: 'none'
      });
      return;
    }
  }
  
  // 执行注册
  isLoading.value = true;
  
  try {
    // 构建注册参数
    const registerData = {
      username: merchantRegisterForm.value.username,
      phone: merchantRegisterForm.value.phone,
      password: merchantRegisterForm.value.password,
      email: merchantRegisterForm.value.email || null, // 如果没有填写邮箱，传null
      shopName: merchantRegisterForm.value.shopName
    };
    
    // 调用商家注册接口
    const response = await http.post('/api/admin/register', registerData);
    
    if (response.code === 200 && response.data) {
      // 注册成功
      uni.showToast({
        title: '注册成功，请登录',
        icon: 'success'
      });
      
      // 自动填充登录表单
      merchantLoginForm.value.username = merchantRegisterForm.value.username;
      merchantLoginForm.value.password = ''; // 出于安全考虑，不自动填充密码
      
      // 切换到登录页面
      currentStep.value = 'merchantLogin';
      merchantLoginType.value = 1; // 切换到密码登录
    } else {
      // 显示错误信息
      uni.showToast({
        title: response.message || '注册失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('商家注册失败:', error);
    uni.showToast({
      title: '注册失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 处理管理员登录
const handleAdminLogin = async () => {
  if (adminLoginType.value === 1) {
    if (!adminLoginForm.value.username || !adminLoginForm.value.password) {
      uni.showToast({
        title: '请输入账号和密码',
        icon: 'none'
      });
      return;
    }
  } else {
    if (!adminLoginForm.value.phone || !adminLoginForm.value.verifyCode) {
      uni.showToast({
        title: '请输入手机号和验证码',
        icon: 'none'
      });
      return;
    }
  }
  
  isLoading.value = true;
  
  try {
    const loginData = {
      loginType: adminLoginType.value,
      username: adminLoginForm.value.username,
      phone: adminLoginForm.value.phone,
      password: adminLoginForm.value.password,
      code: adminLoginForm.value.verifyCode
    };
    
    const response = await http.post('/api/admin/login', loginData);
    
    if (response.code === 200) {
      const adminData = response.data;
      userStore.setUserInfo(adminData);
      userStore.setToken(adminData.token);
      
      popup.value.close();
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 跳转到管理员首页
      uni.reLaunch({
        url: '/pages/dashboard/index'
      });
    } else {
      uni.showToast({
        title: response.message || '登录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 处理管理员注册
const handleAdminRegister = async () => {
  if (!adminRegisterForm.value.username || !adminRegisterForm.value.phone || 
      !adminRegisterForm.value.password || !adminRegisterForm.value.verifyCode) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }
  
  if (adminRegisterForm.value.password.length < 6) {
    uni.showToast({
      title: '密码不能少于6位',
      icon: 'none'
    });
    return;
  }
  
  if (adminRegisterForm.value.password !== adminRegisterForm.value.confirmPassword) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none'
    });
    return;
  }
  
  isLoading.value = true;
  
  try {
    const registerData = {
      username: adminRegisterForm.value.username,
      phone: adminRegisterForm.value.phone,
      password: adminRegisterForm.value.password,
      code: adminRegisterForm.value.verifyCode
    };
    
    const response = await http.post('/api/admin/register', registerData);
    
    if (response.code === 200) {
      uni.showToast({
        title: '注册成功，请登录',
        icon: 'success'
      });
      
      adminLoginForm.value.username = adminRegisterForm.value.username;
      adminLoginForm.value.password = '';
      
      currentStep.value = 'adminLogin';
      adminLoginType.value = 1;
    } else {
      uni.showToast({
        title: response.message || '注册失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '注册失败，请重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 跳过登录
const skipLogin = () => {
  console.log('用户选择跳过登录');
  userStore.userType = 'guest'; // 设置为访客
  // 设置已显示登录弹窗标记
  userStore.setLoginPopupShown();
  popup.value.close();
};

// 暴露方法给父组件
defineExpose({
  open
});

onMounted(() => {
  console.log('登录弹窗组件已加载');
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (cooldownTimer.value) {
    clearInterval(cooldownTimer.value);
  }
  if (merchantCooldownTimer.value) {
    clearInterval(merchantCooldownTimer.value);
  }
  if (adminCooldownTimer.value) {
    clearInterval(adminCooldownTimer.value);
  }
  if (adminRegisterCooldownTimer.value) {
    clearInterval(adminRegisterCooldownTimer.value);
  }
});
</script>

<style>
.login-popup {
  width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.popup-header {
  position: relative;
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
}

.close-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  font-size: 40rpx;
  color: #999;
}

.popup-content {
  padding: 40rpx;
}

.popup-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  margin-bottom: 40rpx;
  display: block;
}

.login-options {
  margin-bottom: 30rpx;
}

.login-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  margin-bottom: 20rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
}

.login-btn[disabled] {
  opacity: 0.6;
}

.merchant-btn {
  background: linear-gradient(to right, #4A90E2, #5CB3FF);
}

.admin-btn {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
}

.skip-login {
  text-align: center;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

/* 登录表单样式 */
.login-tabs {
  display: flex;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.login-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
}

.login-tab.active {
  color: #FF8C42;
  border-bottom: 2rpx solid #FF8C42;
}

/* 商家登录标签样式 */
.merchantLogin .login-tab.active {
  color: #4A90E2;
  border-bottom: 2rpx solid #4A90E2;
}

/* 管理员登录标签样式 */
.adminLogin .login-tab.active {
  color: #FF8C42;
  border-bottom: 2rpx solid #FF8C42;
}

.login-form, .register-form {
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 20rpx;
  position: relative;
}

.input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 40rpx;
  padding: 0 30rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.verify-code {
  display: flex;
  align-items: center;
}

.verify-code .input {
  flex: 1;
}

.code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 24rpx;
  background-color: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 40rpx;
  margin-left: 20rpx;
}

.code-btn[disabled] {
  color: #999;
}

/* 注册表单样式 */
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

/* 底部链接样式 */
.action-links {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

.back-link, .register-link {
  padding: 10rpx;
}

.register-link {
  color: #FF8C42;
}

/* 商家注册链接样式 */
.merchantLogin .register-link {
  color: #4A90E2;
}

/* 管理员注册链接样式 */
.adminLogin .register-link {
  color: #FF8C42;
}
</style>